﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using GalaSoft.MvvmLight.Messaging;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media.Animation;
using MODEL;

namespace Resource.AttachedProperty
{
    public class FrameworkElementBehavior
    {
        public static bool  GetAutoUnRegisterMessenger(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoUnRegisterMessengerProperty);
        }

        public static void SetAutoUnRegisterMessenger(DependencyObject obj, bool  value)
        {
            obj.SetValue(AutoUnRegisterMessengerProperty, value);
        }

        public static readonly DependencyProperty AutoUnRegisterMessengerProperty =
            DependencyProperty.RegisterAttached("AutoUnRegisterMessengerProperty", typeof(bool ), typeof(FrameworkElementBehavior), new PropertyMetadata(false, UnRegisterMessager));

        private static void UnRegisterMessager(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement framework = d as FrameworkElement;

            if (framework == null)
            {
                return;
            }

            RoutedEventHandler hander = new RoutedEventHandler((sender, args) => {
                Messenger.Default.Unregister(framework);
            });
            if ((bool)e.NewValue)
            {

                framework.Unloaded += hander;
            }
            else
            {
                framework.Unloaded -= hander;
            }
        }
    }
}
